package com.hoki.zj.batch.controller;

import com.hoki.zj.batch.domain.BlogInfo;
import com.hoki.zj.batch.service.IBlogInfoService;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/batchJob")
public class JobTestController {

    @Autowired
    IBlogInfoService blogInfoService;

    @Autowired
    SimpleJobLauncher jobLauncher;

    /**
     * Spring 管理下のオブジェクトの中から名前で適切な変数を自動的にセットする
     * myJob
     */
    @Autowired
    Job myJob;

    /**
     * Spring 管理下のオブジェクトの中から名前で適切な変数を自動的にセットする
     * myJobNew
     */
    @Autowired
    Job myJobNew;

    @GetMapping("/testJob")
    public void testJob() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        JobParameters jobParameters = new JobParametersBuilder().toJobParameters();
        jobLauncher.run(myJob, jobParameters);
    }

    @GetMapping("/testJobNew")
    public  void testJobNew(@RequestParam("authorId") String authorId) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {

        JobParameters jobParametersNew = new JobParametersBuilder().addLong("timeNew", System.currentTimeMillis())
                .addString("authorId",authorId)
                .toJobParameters();
        jobLauncher.run(myJobNew,jobParametersNew);

    }

    @GetMapping
    public List<BlogInfo> get() {
        return blogInfoService.findAll();
    }

    @GetMapping("/{id}")
    public BlogInfo findOne(@PathVariable("id") Integer id) {
        return blogInfoService.findOne(id);
    }
}
